package pub.guoxin.oops.common.sms.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pub.guoxin.oops.common.cache.CacheKeyFormatEnums;
import pub.guoxin.oops.common.cache.CacheService;
import pub.guoxin.oops.common.sms.AliyunProperties;
import pub.guoxin.oops.common.sms.enums.SendSmsResponseCode;
import pub.guoxin.oops.common.sms.enums.SmsSignName;
import pub.guoxin.oops.common.sms.enums.SmsTemplate;
import pub.guoxin.oops.common.sms.service.SmsSender;
import pub.guoxin.oops.common.sms.vo.SmsSend;
import pub.guoxin.oops.utils.JsonUtils;
import pub.guoxin.oops.utils.ParseKeyword;

import java.util.Map;
import java.util.Objects;

/**
 * Created by guoxin on 18-3-13.
 */
@Slf4j
@Service
public class SmsSenderImpl implements SmsSender {

    @Autowired
    private AliyunProperties aliyunProperties;
    @Autowired
    private CacheService cacheService;

    @Override
    public boolean send(String mobile, Map<String, String> templateParam, SmsTemplate template, SmsSignName smsSignName) {
        SendSmsRequest request = new SmsSend(mobile, smsSignName,
                template, templateParam).buildRequest();
        log.info("Mobile: {}, TemplateParam: {}, SmsTemplate: {}, SmsSignName: {}", mobile, JsonUtils.obj2json(templateParam), template.toString(), smsSignName.toString());
        log.info("Content: {}", ParseKeyword.parse(template.getContent(), templateParam));
        SendSmsResponse response = null;
        try {
            response = getAcsClient().getAcsResponse(request);
        } catch (ClientException e) {
            log.error("验证码发送错误{}，https://help.aliyun.com/document_detail/55284.html?spm=5176.doc55289.6.556.EHOPEA", e);
            return false;
        }
        if (Objects.isNull(response)) {
            log.info("短信响应对象为空！");
            return false;
        }

        SendSmsResponseCode code = SendSmsResponseCode.findByCode(response.getCode());
        if (Objects.isNull(code)) {
            log.info("未找到对应的响应Code; Code: {}, Message: {}. (https://help.aliyun.com/knowledge_detail/57717.html?spm=a2c4g.11186623.2.9.Gg9I5m)", response.getCode(), response.getMessage());
            return false;
        }
        if (!code.equals(SendSmsResponseCode.OK)) {
            log.info("发送短信失败，Code: {}, Message: {}.https://help.aliyun.com/document_detail/55284.html?spm=5176.doc55289.6.556.EHOPEA", JsonUtils.obj2json(templateParam), code.toString(), code.getDescription());
            return false;
        }

        switch (template.getType()) {
            case CAPTCHA:
                cacheService.put(CacheKeyFormatEnums.SMS_CAPTCHA.key(mobile), templateParam.get("code"), 1000 * 60 * 2);
                log.info("CAPTCHA");
                return true;
            case PROMOTION:
            case NOTIFICATION:
//                SmsInfo notification = new SmsInfo();
//                notification.setId(IdGenerator.nextId("S"));
//                notification.setMobile(mobile);
//                notification.setOutSerialId(response.getBizId());
//                notification.setTemplateCode(template.getCode());
//                notification.setTemplateContent(ParseKeyword.parse(template.getContent(), templateParam));
//                notification.setTemplateName(template.getValue());
//                notification.setTemplateType(template.getType());
//                notification.setVerifyStatus(SmsVerifyStatus.NONE);
//                notification.init();
//                smsInfoMapper.insertSelective(notification);
//                log.info("发送通知短信成功! {}", notification.toString());
                log.info("NOTIFICATION");
                return true;
            default:
                log.info("default ignore");
                return false;
        }

    }

    @Override
    public boolean validate(String mobile, String code) {
        if (cacheService.exists(CacheKeyFormatEnums.SMS_CAPTCHA.key(mobile))) {
            return false;
        }
        String result = cacheService.get(CacheKeyFormatEnums.SMS_CAPTCHA.key(mobile), String.class);
        if (!code.equals(result)) {
            return false;
        }
        return true;
    }

    private IAcsClient getAcsClient() throws ClientException {
        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化ascClient需要的几个参数
        final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
        final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）

        //替换成你的AK
        //初始化ascClient,暂时不支持多 region（请勿修改）
        IClientProfile profile =
                DefaultProfile.getProfile("cn-hangzhou", aliyunProperties.getAccessKeyId(),
                        aliyunProperties.getAccessKeySecret());
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        return new DefaultAcsClient(profile);
    }
}